﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using H2.NET.Common;
using H2.NET.Data.Common;
using H2.NET.Web.Pages.SMD.Model;
using H2.NET.Web.Pages.SMD.Service;
using H2.NET.Web.Workflow.Helper;
using Ultimus.WFServer;

namespace H2.NET.Web.Pages.SMD
{
    public partial class test : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var username = Request.QueryString["username"];
            var password = Request.QueryString["password"];
            if (username == "admin" && password == "111111")
            {
                Response.Write("登录成功");
            }
            else
            {
                Response.Write("登录失败");
            }
            Response.End();
            return;
            if (!IsPostBack)
            {
            }
        }

        /// <summary>
        /// 初始化t_smd_Relation表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button1_Click(object sender, EventArgs e)
        {
            Expression exp = new Expression();
            exp = t_StoreMasterData._BusinessKey != "" & t_StoreMasterData._BusinessProcess != "";
            var storeMasterDatas = exp.List<t_StoreMasterData>();
            foreach (var storeMasterData in storeMasterDatas)
            {
                try
                {
                    switch (storeMasterData.BusinessProcess)
                    {
                        //1.新开门店
                        case Constant.PROCESS_STORE:
                            InitStoreProcess(storeMasterData);
                            break;
                        // 2.经销商更换
                        case Constant.PROCESS_CHANGEDEALER:
                            InitChangeDealerProcess(storeMasterData);
                            break;
                        // 3.门店关闭/降级
                        case Constant.PROCESS_CHANGELEVEL:
                            InitDegradeStoreProcess(storeMasterData);
                            break;
                        // 4.设备三方转移
                        case Constant.PROCESS_TRANSFER:
                            InitTransferProcess(storeMasterData);
                            break;
                        // 5.设备报废/库存
                        case Constant.PROCESS_CHANGESTATUS:
                            InitDiscardDeviceProcess(storeMasterData);
                            break;
                        // 6.其他信息更改
                        case Constant.PROCESS_CHANGEOTHER:
                            InitChangeOtherProcess(storeMasterData);
                            break;
                    }
                }
                catch (Exception ex)
                {
                    Logging.GetLogger().Error(ex);
                }
            }
        }

        // ok
        private void InitStoreProcess(t_StoreMasterData storeMasterData)
        {
            var incident = new Incident();
            incident.LoadIncident(storeMasterData.Process, storeMasterData.Incident.Value);


            var relation = StoreMasterDataToRelation(storeMasterData);

            switch (storeMasterData.Process)
            {
                case "New Store Application":
                    {
                        break;
                    }
                case "Store Deposit Receive":
                    {
                        // 更新设备ID
                        object FullsetSN = null;
                        string error;
                        incident.GetVariableValue("FullsetSN", out FullsetSN, out error);

                        if (FullsetSN != null)
                        {
                            relation.FullsetSN = FullsetSN.ToString();
                            var device = (t_smd_Device._FullSetSN == FullsetSN).ListFirst<t_smd_Device>(Storage.Context3);
                            relation.DeviceID = device.DeviceID.ToString();
                        }
                        break;
                    }
                case "Store Data Change":
                    {
                        // 获取门店主数据变更日志
                        var assessments = AssessmentService.FindByPI(storeMasterData.Process, storeMasterData.Incident.Value);
                        var changelogs = (t_StoreDataChangeLog._AssessmentID.In(assessments.Select(a => a.ID).ToArray())).List<t_StoreDataChangeLog>().OrderByDescending(t => t.LogID).ToList();

                        // 查询StoreName、StoreStatus、StoreType是否变更过
                        var storeName = changelogs.FirstOrDefault(t => t.FieldName == "StoreName");
                        if (storeName != null)
                        {
                            relation.StoreName = storeName.AfterValue;
                        }
                        var storeStatus = changelogs.FirstOrDefault(t => t.FieldName == "StoreStatus");
                        if (storeStatus != null)
                        {
                            relation.StoreStatus = storeStatus.AfterValue;
                        }
                        var storeType = changelogs.FirstOrDefault(t => t.FieldName == "StoreType");
                        if (storeType != null)
                        {
                            relation.StoreType = storeType.AfterValue;
                        }

                        break;
                    }
            }

            Storage.Save(relation);
        }

        private void InitChangeDealerProcess(t_StoreMasterData storeMasterData)
        {
            var assessments = AssessmentService.FindByPI(storeMasterData.Process, storeMasterData.Incident.Value);
            var changelogs = (t_StoreDataChangeLog._AssessmentID.In(assessments.Select(a => a.ID).ToArray())).List<t_StoreDataChangeLog>().OrderByDescending(t => t.LogID).ToList();

            var ass = AssessmentService.GetBySubmitData(storeMasterData.Process, storeMasterData.Incident.Value);
            TaskAPI taskapi = new TaskAPI() { TaskID = TaskHelper.GetTaskId(storeMasterData.Process,storeMasterData.Incident.Value,ass.Step) };
           

            var assIds = AssessmentService.GetIdsByTaskApi(taskapi);
           
            var storeIds = changelogs.Select(t => Utils.StrToInt(t.DataID, 0)).ToList();
            var stores = StoreService.FindSmdByStoreIds(storeIds);
            var dealerID_new = storeMasterData.DealerCode.Split('|')[0];
            var delaerId_old = storeMasterData.DealerCode.Split('|')[1];
            var oldDealer = DealerService.GetById(Utils.StrToInt(delaerId_old, 0));
            var dealer = DealerService.GetById(Utils.StrToInt(dealerID_new, 0));

            var deviceIds = storeMasterData.DispenseModel.Split(',').ToList();
            var dealers = new List<t_smd_Dealer>();
            var devices = new List<t_smd_Device>();
            for (var i = 0; i < stores.Count; i++)
            {
                foreach (var log in changelogs)
                {
                    var store = StoreService.GetSmdStoreById(Utils.StrToInt(log.DataID, 0));
                    if (!stores.Select(t => t.StoreID).Contains(store.StoreID))
                    {
                        stores.Add(store);
                    }
                    
                }

            }
            foreach (var store in stores)
            {
                var _devices = (t_smd_Device._StoreID == store.StoreID).List<t_smd_Device>(Storage.Context3);
                foreach (var device in _devices)
                {
                    devices.Add(device);
                }
            }
            var smdDevices = (t_smd_Device._DeviceID.In(deviceIds)).List<t_smd_Device>(Storage.Context3).ToList();
            BusinessService.saveProcessRelation(taskapi, ass, null, null, dealer, oldDealer, stores, smdDevices, null);

        }

        // ok
        private void InitDegradeStoreProcess(t_StoreMasterData storeMasterData)
        {
            var relation = StoreMasterDataToRelation(storeMasterData);

            // 获取门店主数据变更日志
            var assessments = AssessmentService.FindByPI(storeMasterData.Process, storeMasterData.Incident.Value);
            var changelogs = (t_StoreDataChangeLog._AssessmentID.In(assessments.Select(a => a.ID).ToArray())).List<t_StoreDataChangeLog>().OrderByDescending(t => t.LogID).ToList();

            // 查询StoreStatus、StoreType是否变更过
            var storeStatus = changelogs.FirstOrDefault(t => t.FieldName == "StoreStatus");
            if (storeStatus != null)
            {
                relation.StoreStatus = storeStatus.AfterValue;
            }
            var storeType = changelogs.FirstOrDefault(t => t.FieldName == "StoreType");
            if (storeType != null)
            {
                relation.StoreType = storeType.AfterValue;
            }


            Storage.Save(relation);
        }

        // ok
        private void InitTransferProcess(t_StoreMasterData storeMasterData)
        {

            var incident = new Incident();
            incident.LoadIncident(storeMasterData.Process, storeMasterData.Incident.Value);

            var relation = StoreMasterDataToRelation(storeMasterData);

            string error;

            object blankVlue = null;
            incident.GetVariableValue("BlankVlue", out blankVlue, out error);

            var val = blankVlue.ToString().Split('|');
            var deviceIds = val[0];
            var outStoreId = val[1];
            var inStoreId = val[2];

            var outStore = StoreService.GetSmdStoreById(Utils.ObjToInt(outStoreId, 0));
            var inStore = StoreService.GetSmdStoreById(Utils.ObjToInt(inStoreId, 0));
            var outDealer = DealerService.GetById(outStore.DealerID.Value);
            var inDealer = DealerService.GetById(inStore.DealerID.Value);
            var device = DeviceService.GetSmdDeviceById(Utils.ObjToInt(deviceIds, 0));
            relation.AuthID = outStore.AuthID + "," + inStore.AuthID;
            relation.StoreName = outStore.StoreName + "," + inStore.StoreName;
            relation.StoreStatus = outStore.StoreStatus + "," + inStore.StoreStatus;
            relation.StoreType = outStore.StoreType + "," + inStore.StoreType;
            relation.FullsetSN = device.FullSetSN;
            relation.Region = outStore.Region + "," + inStore.Region;
            relation.Province = outStore.Province + "," + inStore.Province;
            relation.City = outStore.CityName + "," + inStore.CityName;
            relation.StoreID = outStore.StoreID.ToString() + "," + inStore.StoreID.ToString();
            relation.DeviceID = deviceIds;
            relation.DealerID = outDealer.DealerID.ToString() + "," + inDealer.DealerID.ToString();
            relation.DealerCode = outDealer.DealerCode.ToString() + "," + inDealer.DealerCode.ToString();


            Storage.Save(relation);
        }

        // ok
        private void InitDiscardDeviceProcess(t_StoreMasterData storeMasterData)
        {

            var incident = new Incident();
            incident.LoadIncident(storeMasterData.Process, storeMasterData.Incident.Value);

            var relation = StoreMasterDataToRelation(storeMasterData);
            
            string error;

            object storeId = null;
            incident.GetVariableValue("BlankVlue", out storeId, out error);

            object deviceId = null;
            incident.GetVariableValue("DeviceID", out deviceId, out error);

            var store = StoreService.GetSmdStoreById(Utils.ObjToInt(storeId, 0));
            var device = DeviceService.GetSmdDeviceById(Utils.ObjToInt(deviceId, 0));
            var dealer = DealerService.GetById(store.DealerID.Value);
            relation.AuthID = store.AuthID;
            relation.StoreName = store.StoreName;
            relation.StoreType = store.StoreType;
            relation.FullsetSN = device.FullSetSN;
            relation.Region = store.Region;
            relation.Province = store.Province;
            relation.City = store.CityName;
            relation.StoreID = store.StoreID.ToString();
            relation.DeviceID = deviceId.ToString();
            relation.DealerID = store.DealerID.ToString();
            relation.DealerCode = dealer.DealerCode;

            // 获取门店主数据变更日志
            var assessments = AssessmentService.FindByPI(storeMasterData.Process, storeMasterData.Incident.Value);
            var changelogs = (t_StoreDataChangeLog._AssessmentID.In(assessments.Select(a => a.ID).ToArray())).List<t_StoreDataChangeLog>().OrderByDescending(t => t.LogID).ToList();

            // 查询设备的 Status
            var storeStatus = changelogs.FirstOrDefault(t => t.FieldName == "Status");
            if (storeStatus != null)
            {
                relation.StoreStatus = storeStatus.AfterValue;
            }

            Storage.Save(relation);
        }

        private void InitChangeOtherProcess(t_StoreMasterData storeMasterData)
        {
            var assessments = AssessmentService.FindByPI(storeMasterData.Process, storeMasterData.Incident.Value);
            var changelogs = (t_StoreDataChangeLog._AssessmentID.In(assessments.Select(a => a.ID).ToArray())).List<t_StoreDataChangeLog>().OrderByDescending(t => t.LogID).ToList();
            var Category = changelogs[0].Category;
            TaskAPI taskapi = new TaskAPI() { TaskID = TaskHelper.GetTask(storeMasterData.Process, storeMasterData.Incident.Value).strTaskId };
            var assIds = AssessmentService.GetIdsByTaskApi(taskapi);
            var ass = AssessmentService.GetBySubmitData(storeMasterData.Process, storeMasterData.Incident.Value);

            var type = Category.ToLower().Contains("store") && !Category.ToLower().Contains("contract") ? "store" : Category.ToLower().Contains("device") && !Category.ToLower().Contains("contract") ? "device" : Category.ToLower().Contains("contract") ? "contract" : "";
            var isBatch = Category.ToLower().Contains("batch");
            if (!isBatch)
            {
                var storeid = 0;
                var store = new t_smd_Store();
                var dealer = new t_smd_Dealer();
                t_smd_Device device = null;
                switch (type)
                {
                    case "store":
                        storeid = Utils.StrToInt(changelogs[0].DataID, 0);
                        store = StoreService.GetSmdStoreById(storeid);
                        dealer = DealerService.GetById(store.DealerID.Value);
                        BusinessService.saveProcessRelation(taskapi, ass, store, null, dealer, null, null, null, null);
                        break;
                    case "device":
                        device = DeviceService.GetSmdDeviceById(Utils.StrToInt(changelogs[0].DataID, 0));
                        store = StoreService.GetSmdStoreById(device.StoreID.Value);
                        dealer = DealerService.GetById(store.DealerID.Value);
                        BusinessService.saveProcessRelation(taskapi, ass, store, device, dealer, null, null, null, null);
                        break;
                    case "contract":
                        var storeLog = changelogs.Where(t => t.Category.Contains("store")).ToList();
                        var deviceLog = changelogs.Where(t => t.Category.Contains("device")).ToList();
                        if (storeLog.Count > 0)
                        {
                            var storeContract = ContractService.GetContractByID(Utils.StrToInt(storeLog[0].DataID, 0));
                            store = StoreService.GetSmdStoreById(storeContract.StoreID.Value);
                            dealer = DealerService.GetById(store.DealerID.Value);
                        }
                        if (deviceLog.Count > 0)
                        {
                            var deviceContract = (t_smd_ContractDevice._ContractDeviceID == Utils.StrToInt(deviceLog[0].DataID, 0)).ListFirst<t_smd_ContractDevice>();
                            device = DeviceService.GetSmdDeviceById(deviceContract.DeviceID);
                            store = StoreService.GetSmdStoreById(device.StoreID.Value);
                            dealer = DealerService.GetById(store.DealerID.Value);
                        }
                        BusinessService.saveProcessRelation(taskapi, ass, store, device, dealer, null, null, null, null);
                        break;
                }
            }
            else 
            {
                var storeid = 0;
                var store = new t_smd_Store();
                var dealer = new t_smd_Dealer();
                var stores = new List<t_smd_Store>();
                var dealers = new List<t_smd_Dealer>();
                t_smd_Device device = null;
                var devices = new List<t_smd_Device>();
                switch (type)
                {
                    case "store":
                    foreach (var log in changelogs) 
                    {
                        store = StoreService.GetSmdStoreById(Utils.StrToInt(log.DataID,0));
                        dealer = DealerService.GetById(store.DealerID.Value);
                        if (!stores.Select(t => t.StoreID).Contains(store.StoreID))
                        {
                            stores.Add(store);
                        }
                        if (!dealers.Select(t => t.DealerID).Contains(dealer.DealerID)) 
                        {
                            dealers.Add(dealer);
                        }
                        
                    }

                    dealers = dealers.Distinct().ToList<t_smd_Dealer>();
                    BusinessService.saveProcessRelation(taskapi, ass, null, null, null, null, stores, null, dealers);
                    break;
                    case "device":
                    devices = new List<t_smd_Device>();

                    foreach (var log in changelogs)
                    {
                        device = DeviceService.GetSmdDeviceById(Utils.StrToInt(log.DataID, 0));
                        store = StoreService.GetSmdStoreById(device.StoreID.Value);
                        dealer = DealerService.GetById(store.StoreID);
                        if (!dealers.Select(t => t.DealerID).Contains(dealer.DealerID))
                        {
                            dealers.Add(dealer);
                        }
                        if (!stores.Select(t => t.StoreID).Contains(store.StoreID)) 
                        {
                            stores.Add(store);
                        }
                        if (!devices.Select(t => t.DeviceID).Contains(device.DeviceID))
                        {
                            devices.Add(device);
                        }
                    }
                    stores = stores.Distinct().ToList<t_smd_Store>();
                    dealers = dealers.Distinct().ToList<t_smd_Dealer>();

                    BusinessService.saveProcessRelation(taskapi, ass, null, null, null, null, stores, devices, dealers);
                    break;
                    case "contract":
                    var storeLog = changelogs.Where(t => t.Category.Contains("store")).ToList();
                    var deviceLog = changelogs.Where(t => t.Category.Contains("device")).ToList();
                    foreach (var log in storeLog)
                    {
                        var contract = ContractService.GetContractByID(Utils.StrToInt(log.DataID, 0));
                        store = StoreService.GetSmdStoreById(contract.StoreID.Value);
                        dealer = DealerService.GetById(store.DealerID.Value);
                        if (!dealers.Select(t => t.DealerID).Contains(dealer.DealerID))
                        {
                            dealers.Add(dealer);
                        }
                        if (!stores.Select(t => t.StoreID).Contains(store.StoreID)) 
                        {
                            stores.Add(store);
                        }     
                    }
                    dealers = dealers.Distinct().ToList<t_smd_Dealer>();

                    devices = new List<t_smd_Device>();
                    foreach (var log in deviceLog)
                    {
                        device = DeviceService.GetSmdDeviceById(Utils.StrToInt(log.DataID, 0));
                        if(!devices.Select(t=>t.DeviceID).Contains(device.DeviceID))
                        {
                            devices.Add(device);
                        }
                    }

                    BusinessService.saveProcessRelation(taskapi, ass, null, null, null, null, stores, devices, dealers);
                    break;
                }
            }
        }

        // Util
        private t_smd_Relation StoreMasterDataToRelation(t_StoreMasterData storeMasterData)
        {
            Debug.Assert(storeMasterData.Incident != null, "storeMasterData.Incident != null");

            var relation = (t_smd_Relation._BusinessKey == storeMasterData.BusinessKey).ListFirst<t_smd_Relation>();
            if (relation != null)
            {
                return relation;
            }

            relation = new t_smd_Relation();
            relation.BusinessKey = storeMasterData.BusinessKey;
            relation.Process = storeMasterData.Process;
            relation.Incident = storeMasterData.Incident.Value;
            relation.BusinessProcess = storeMasterData.BusinessProcess;
            relation.EapproveSN = storeMasterData.SerialNumber;
            relation.EapproveData = storeMasterData.StoreApprovedDate == null
                ? ""
                : storeMasterData.StoreApprovedDate.Value.ToString("yyyy-MM-dd");
            relation.AuthID = storeMasterData.AuthID;
            relation.StoreName = storeMasterData.StoreName;
            relation.StoreStatus = storeMasterData.Status;
            relation.StoreType = storeMasterData.StoreType;
            relation.FullsetSN = storeMasterData.DeviceFullSetSN;
            relation.Region = storeMasterData.AreaName;
            relation.Province = storeMasterData.ProvinceName;
            relation.City = storeMasterData.CityName;
            relation.StoreID = storeMasterData.StoreId == null ? "" : storeMasterData.StoreId.Value.ToString();
            relation.DeviceID = storeMasterData.DeviceId == null ? "" : storeMasterData.DeviceId.Value.ToString();
            relation.DealerCode = storeMasterData.DealerCode;

            if (!string.IsNullOrEmpty(relation.DealerCode))
            {
                relation.DealerID = DealerService.GetByCode(relation.DealerCode).DealerID.ToString();
            }

            return relation;
        }

    }
}